package com.biostime.qdingding.modules.qd.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.print.DocFlavor.URL;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.biostime.qdingding.common.config.Global;
import com.biostime.qdingding.common.persistence.Page;
import com.biostime.qdingding.common.utils.DateUtils;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.entity.Album;
import com.biostime.qdingding.modules.qd.entity.Center;
import com.biostime.qdingding.modules.qd.entity.Classroom;
import com.biostime.qdingding.modules.qd.entity.Contract;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.entity.Course.PriceType;
import com.biostime.qdingding.modules.qd.entity.CourseOrder;
import com.biostime.qdingding.modules.qd.entity.Coursefree;
import com.biostime.qdingding.modules.qd.entity.Courselevel;
import com.biostime.qdingding.modules.qd.entity.Courseprice;
import com.biostime.qdingding.modules.qd.entity.Coursesection;
import com.biostime.qdingding.modules.qd.entity.Courseserial;
import com.biostime.qdingding.modules.qd.entity.Coursetheme;
import com.biostime.qdingding.modules.qd.entity.Member;
import com.biostime.qdingding.modules.qd.entity.MemberCoupon;
import com.biostime.qdingding.modules.qd.entity.Student;
import com.biostime.qdingding.modules.qd.entity.Teacher;
import com.biostime.qdingding.modules.qd.push.MsgTemplate;
import com.biostime.qdingding.modules.qd.push.MsgTemplate.CourseTimeChanged;
import com.biostime.qdingding.modules.qd.service.AlbumService;
import com.biostime.qdingding.modules.qd.service.ClassroomService;
import com.biostime.qdingding.modules.qd.service.ContractService;
import com.biostime.qdingding.modules.qd.service.CouponService;
import com.biostime.qdingding.modules.qd.service.CourseOrderService;
import com.biostime.qdingding.modules.qd.service.CourseService;
import com.biostime.qdingding.modules.qd.service.CoursefreeService;
import com.biostime.qdingding.modules.qd.service.CourselevelService;
import com.biostime.qdingding.modules.qd.service.CoursepriceService;
import com.biostime.qdingding.modules.qd.service.CoursesectionService;
import com.biostime.qdingding.modules.qd.service.CourseserialService;
import com.biostime.qdingding.modules.qd.service.CoursethemeService;
import com.biostime.qdingding.modules.qd.service.MemberCouponService;
import com.biostime.qdingding.modules.qd.service.MemberService;
import com.biostime.qdingding.modules.qd.service.MessageService;
import com.biostime.qdingding.modules.qd.service.PrivilegeService;
import com.biostime.qdingding.modules.qd.service.StudentService;
import com.biostime.qdingding.modules.qd.service.TeacherService;
import com.biostime.qdingding.modules.qd.service.TransrecordService;
import com.biostime.qdingding.modules.qd.utils.CalendarUtils;
import com.biostime.qdingding.modules.qd.utils.CalendarUtils.WeekCell;
import com.biostime.qdingding.modules.qd.utils.CalendarUtils.WeekInfo;
import com.biostime.qdingding.modules.sys.entity.Area;
import com.biostime.qdingding.modules.sys.entity.User;
import com.biostime.qdingding.modules.sys.service.AreaService;
import com.biostime.qdingding.modules.sys.utils.UserUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;

/**
 * 排课表Controller
 * @author phil
 * @version 2015-11-11
 */
@Controller
@RequestMapping(value = "${adminPath}/qd/course")
public class CourseController extends BaseController {

	@Autowired
	private CoursesectionService coursesecionService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private CourselevelService courselevelService;
	@Autowired
	private CourseserialService courseserialService;
	@Autowired
	private ClassroomService classroomService;
	@Autowired
	private CoursesectionService coursesectionService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private CoursethemeService coursethemeService;
	@Autowired
	private CoursepriceService coursepriceService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private CourseOrderService courseOrderService;
	@Autowired 
	AlbumService albumService;
	@Autowired
	private CoursefreeService coursefreeService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private TransrecordService transrecordService;
	@Autowired 
	private PrivilegeService privilegeService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private ContractService contractService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private MemberCouponService memberCouponService;
	@Autowired
	private CouponService couponService;
	
	@ModelAttribute
	public Course get(@RequestParam(required=false) String id) {
		Course entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = courseService.get(id);
		}
		if (entity == null){
			entity = new Course();
		}
		return entity;
	}
	
	@RequestMapping(value = {"ajax"})
	public void serial(HttpServletRequest request, HttpServletResponse response){
		try {
			String method = request.getParameter("method");
			
			if(StringUtils.isEmpty(method)){
				response.getWriter().write("缺少method参数");
				return;
			}
			String levelId,serialId,themeId;
			
			ObjectMapper mapper = new ObjectMapper();
			
			switch(method){
			case "level":
				levelId = request.getParameter("levelId");
				response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n","","请选择..."));
				
				if(StringUtils.isNotBlank(levelId)){
					List<Courseserial> list = courseserialService.findListByLevel(levelId);
					for(Courseserial s : list){
						response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n", s.getId(),s.getName()));
					}
				}
				break;
			case "theme": 
				levelId = request.getParameter("levelId");
				serialId = request.getParameter("serialId");
				response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n","","请选择..."));
				
				if(StringUtils.isNotBlank(levelId)){
					Coursetheme ext = new Coursetheme();
					ext.setLevel(new Courselevel(levelId));
					ext.setSerial(new Courseserial(serialId));
					List<Coursetheme> list = coursethemeService.findList(ext);
					
					for(Coursetheme t : list){
						response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n", t.getId(),t.getName()));
					}
				}
				break;
			case "themeDesc":
				themeId = request.getParameter("themeId");
				Coursetheme theme = coursethemeService.get(themeId);
				if(theme!=null)
					response.getWriter().write(theme.getDescription());
				break;
			case "priceType":
				String centerId = request.getParameter("centerId");
				String priceType = request.getParameter("priceType");
				
				Courseprice price = new Courseprice();
				price.setCenter(new Center(centerId));
				price.setType(StringUtils.toInteger(priceType));
				
				List<Courseprice> prices = coursepriceService.findList(price);
				List<PriceType> types = Lists.newArrayList();
				
				
				for(Courseprice p : prices){
					PriceType type = new PriceType();
					type.setId(p.getId());
					//type.setType(p.getType());
					type.setStarton(p.getStarton());
					type.setEndon(p.getEndon());
					type.setPrice(p.getPrice());
					types.add(type);
				}
				
				if(types!=null && types.size()>0){
					response.getWriter().write(mapper.writeValueAsString(types));
				}
				
				break;
			case "week":
				String yearStr = request.getParameter("year");
				
				Calendar now = Calendar.getInstance();
				
				int year = now.get(Calendar.YEAR);
				if(!StringUtils.isEmpty(yearStr)){
					year = StringUtils.toInteger(yearStr);
				}
				
				List<WeekInfo> infos = CalendarUtils.getWeeksInYear(year);
				
				List<String> res = Lists.newArrayList();
				for(WeekInfo week : infos){
					String r = String.format("%s:%s", week.text(),week.value());
					res.add(r);
				}
				if(infos!=null){
					response.setCharacterEncoding("utf-8");
					response.getWriter().write(mapper.writeValueAsString(res));
				}
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = {"choose"})
	public String choose(Student student, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Student> page =new Page<Student>(request, response);
		student.setCenter(UserUtils.getCenter());
		student.setPage(page);
		page.setList(studentService.findContractStatusStudent(student));
		
		model.addAttribute("page", page);
		model.addAttribute("student", student);
		 
		return "modules/qd/courseChoose";
	}
	
	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = {"freeorder"})
	public String freeOrder(Contract contract,HttpServletRequest request, HttpServletResponse response, Model model) {
		Area province = new Area();
		province.setLayer(2);
		List<Area> provinceList = areaService.findList(province);
		
		model.addAttribute("courseId", request.getParameter("courseid"));
		if(request.getParameter("message") != null && !request.getParameter("message").equals("")){
			String message = request.getParameter("message");
			model.addAttribute("message", message);
		}
		model.addAttribute("provinceList", provinceList);
		return "modules/qd/freeOrder";
	}
	
	@RequestMapping(value = {"freeorderform"})
	@ResponseBody
	public HashMap<String, String>  freeOrderForm(@RequestParam(required = false) String mode,Contract contract,HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, String> map = new HashMap<String, String>();
		if(mode != null){
			if(mode.equalsIgnoreCase("exist")){//验证手机号所存在的合同
				String mobile = request.getParameter("mobile");
				Member member = new Member();
				member.setMobile(mobile);
				contract.setMember(member);
				contract = contractService.getByMobileStatus(contract);
				if(contract != null){//合同不为空
					if(!StringUtils.isEmpty(contract.getType()) && contract.getType().equalsIgnoreCase("free")){//免费合同
						CourseOrder courseOrder = new CourseOrder();
						courseOrder.setContract(contract);
						int count = courseOrderService.getCouponCount(courseOrder);
						map.put("ok", "0");
						member = memberService.get(contract.getMember());
						map.put("contractId",contract.getId());
						map.put("province", member.getAreaProvice().getName());
						map.put("provinceId", member.getAreaProvice().getId());
						map.put("city", member.getAreaCity().getName());
						map.put("cityId", member.getAreaCity().getId());
						map.put("area", member.getAreaArea().getName());
						map.put("areaId", member.getAreaArea().getId());
						map.put("nikename", member.getNikename());
						map.put("count", String.valueOf(count));
					}else{//正常合同
						map.put("ok", "1");
					}
				}else{//合同为空
					map.put("ok", "-1");
				}
			}
		}
		return map;
	}
	
	@RequestMapping("freeorderdispose")
	public String freeOrderDispose(Contract contract,HttpServletRequest request,HttpServletResponse response,Model model) throws Exception{
		logger.info("免费预约=====================courseId="+request.getParameter("courseid"));
		logger.info("免费预约=====================contractId="+contract.getId());
		String message = "";
		if(StringUtils.isEmpty(contract.getId())){
			message = courseOrderService.freeOrder(contract, request.getParameter("courseid"));
		}else{
			message = courseOrderService.freeOrderCoupon(contract, request.getParameter("courseid"));
		}
		System.out.println("====================="+message);
		return "redirect:"+Global.getAdminPath()+"/qd/course/freeorder?courseid="+request.getParameter("courseid")+"&message="+URLEncoder.encode(message,"UTF-8");
	}
	
	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = {"giftorder"})
	public String giftOrder(Contract contract,HttpServletRequest request, HttpServletResponse response, Model model) {
		Area province = new Area();
		province.setLayer(2);
		List<Area> provinceList = areaService.findList(province);
		
		model.addAttribute("courseId", request.getParameter("courseid"));
		if(request.getParameter("message") != null && !request.getParameter("message").equals("")){
			String message = request.getParameter("message");
			model.addAttribute("message", message);
		}
		model.addAttribute("provinceList", provinceList);
		return "modules/qd/giftOrder";
	}
	
	@RequestMapping(value = {"giftorderform"})
	@ResponseBody
	public HashMap<String, Object>  giftOrderForm(@RequestParam(required = false) String mode,Contract contract,HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		if(mode != null){
			if(mode.equalsIgnoreCase("exist")){//验证手机号所存在的合同
				String mobile = request.getParameter("mobile");
				Member member = new Member();
				member.setMobile(mobile);
				contract.setMember(member);
				contract = contractService.getByMobileStatus(contract);
				if(contract != null){//合同不为空
						CourseOrder courseOrder = new CourseOrder();
						courseOrder.setContract(contract);
						MemberCoupon memberCoupon = new MemberCoupon();
						memberCoupon.setMemberId(Integer.parseInt(contract.getMember().getId()));
						member.setCenter(UserUtils.getCenter());
						memberCoupon.setMember(member);
						List<MemberCoupon> memberCoupons = memberCouponService.findGiftByMemberId(memberCoupon);
						List<String> htmlList = new ArrayList<String>();
						for(MemberCoupon temp : memberCoupons){
							htmlList.add("<option value='"+temp.getId()+"' >"+temp.getCoupon().getName()+"</option>");
						}
						map.put("ok", "0");
						map.put("couponList",htmlList);
						member = memberService.get(contract.getMember());
						map.put("contractId",contract.getId());
						map.put("province", member.getAreaProvice().getName());
						map.put("provinceId", member.getAreaProvice().getId());
						map.put("city", member.getAreaCity().getName());
						map.put("cityId", member.getAreaCity().getId());
						map.put("area", member.getAreaArea().getName());
						map.put("areaId", member.getAreaArea().getId());
						map.put("nikename", member.getNikename());
				}else{//合同为空
					map.put("ok", "-1");
				}
			}
		}
		return map;
	}
	
	@RequestMapping("giftorderdispose")
	public String giftOrderDispose(Contract contract,HttpServletRequest request,HttpServletResponse response,Model model, RedirectAttributes redirectAttributes) throws Exception{
		logger.info("赠课预约=====================courseId="+request.getParameter("courseid"));
		logger.info("赠课预约=====================contractId="+contract.getId());
		String message = "";
		if(StringUtils.isEmpty(contract.getId())){
			message =  "该手机号没有合同,需要新建合同才能预约";
		}else{
			message = courseOrderService.giftOrderCoupon(contract, request.getParameter("courseid"));
		}
		System.out.println("====================="+message);
		
		System.out.println("redirect:"+Global.getAdminPath()+"/qd/course/giftorder?courseid="+request.getParameter("courseid")+"&message="+URLEncoder.encode(message,"UTF-8"));
		
		//redirectAttributes.addAttribute("message", message);
		
		return "redirect:"+Global.getAdminPath()+"/qd/course/giftorder?courseid="+request.getParameter("courseid")+"&message="+URLEncoder.encode(message,"UTF-8");
	}
	
	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = {"list", ""})
	public String list(Center center, HttpServletRequest request, HttpServletResponse response, Model model) {
		ServletContext servletContext = request.getServletContext();
				
		Calendar calendar = Calendar.getInstance();
		calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周的开始
		calendar.setTime(new Date());
		
		String mode = request.getParameter("mode");
		String action = request.getParameter("action");
		
		String viewName = "";
		
		if(mode == null || mode.equals("week")){
			//周日历
			viewName = "modules/qd/courseListWeek";
			
			String yearStr = request.getParameter("year");
			String weekOfYearStr = request.getParameter("week");
			
			//当前年
			int yearNow = calendar.get(Calendar.YEAR);
			
			//年列表取当前年前后5年
			/*List<Integer> yearList = Lists.newArrayList(); 
			for(int i=yearNow+5;i>=yearNow-5;i--){
				yearList.add(i);
			}*/
			
			//当前周
			int weekNow = calendar.get(Calendar.WEEK_OF_YEAR);
			//bug:一年最后一周跨越2年，年份＋1
			int monthNow = calendar.get(Calendar.MONTH);
			if(weekNow==1 && monthNow!=Calendar.JANUARY){
				yearNow+=1;
			}
			
			//请求年
			int year = yearNow;
			if(!StringUtils.isEmpty(yearStr)){
				year = StringUtils.toInteger(yearStr);
			}
			
			//请求周
			int week = weekNow;
			if(!StringUtils.isEmpty(weekOfYearStr)){
				week = StringUtils.toInteger(weekOfYearStr);
			}
			
			List<WeekInfo> weekList = CalendarUtils.getWeeksInYear(year);
			/*List<Integer> weekList = Lists.newArrayList();
			int weeksInYear = CalendarUtils.getWeeksInYear(year,week);
			for(int i=1;i<=weeksInYear;i++){
				weekList.add(i);
			}*/
			
			//上周
			int weekPre = week, yearPre = year;
			if((week-1)<=0){
				yearPre = year-1;
				
				List<WeekInfo> preWeekList = CalendarUtils.getWeeksInYear(yearPre);
				weekPre = preWeekList.size();
			}else{
				weekPre -= 1;
			}
			
			//下周
			int weekNext = week, yearNext = year;
			if((week+1)>weekList.size()){
				weekNext = 1;
				yearNext = year+1;
			}else{
				weekNext += 1;
			}
			
			WeekInfo weekInfo = CalendarUtils.getWeek2(year,week);
			
			//课程阶段
			List<Coursesection> sections = coursesecionService.findList(new Coursesection());
			
			Course demo = new Course();
			//修改主题
			if(!StringUtils.isEmpty(action) && action.equals("theme")){
				
				String l1 = request.getParameter("l1");
				String lx = request.getParameter("lx");
				
				if(!(StringUtils.isEmpty(l1) && StringUtils.isEmpty(lx))){
					List<Course> courseToChangeThemes = courseService.findListByWeek(demo, weekInfo.getStart(), weekInfo.getEnd());
					for(Course course : courseToChangeThemes){
						
						if(!StringUtils.isEmpty(l1) && course.getClevel().equals("L1")){
							List<Map<String,String>> theme = coursethemeService.getTheme(course.getSerial(), course.getClevel(), l1, course.getCenterId());
							if(theme!=null && theme.size()>0){
								int themeId = StringUtils.toInteger(theme.get(0).get("id"));
								String themeName = theme.get(0).get("name").toString();
								String themeDesc = theme.get(0).get("desc").toString();
								course.setThemeId(themeId);
								course.setTheme(themeName);
								course.setThemeDesc(themeDesc);
								
								courseService.save(course);
							}
						}
						
						if(!StringUtils.isEmpty(lx) && !course.getClevel().equals("L1")){
							List<Map<String,String>> theme = coursethemeService.getTheme(course.getSerial(), course.getClevel(), lx, course.getCenterId());
							
							if(theme!=null && theme.size()>0){
								int themeId = StringUtils.toInteger(theme.get(0).get("id"));
								String themeName = theme.get(0).get("name").toString();
								String themeDesc = theme.get(0).get("desc").toString();
								course.setThemeId(themeId);
								course.setTheme(themeName);
								course.setThemeDesc(themeDesc);
								
								courseService.save(course);
							}
						}
					}
				}
			}
			
			//已经排好课程
			List<Course> courseList = courseService.findListByWeek(demo, weekInfo.getStart(), weekInfo.getEnd());
			Map<String,List<Course>> courseMap = new HashMap<String, List<Course>>();
			for(Course course : courseList){ 
				String key = String.format("%s-%s", course.getSectionId(),DateUtils.formatDate(course.getOndate(),"yyyy-MM-dd"));
				
				if(!courseMap.containsKey(key)){ 
					List<Course> childs = Lists.newArrayList();
					courseMap.put(key, childs);
				}
				
				courseMap.get(key).add(course);
			}
			
			/**表格标题**/
			Vector<Vector<String>> courses = new Vector<Vector<String>>();  
			Vector<String> title = new Vector<String>();
			for(int i=0;i<=weekInfo.getCells().size();i++){
				if(i==0) {
					title.add("");
				}else
				{
					WeekCell cell = weekInfo.getCells().get(i-1);
					title.add(cell.getName() + DateUtils.formatDate(cell.getDate(), "(MM.dd)"));
				}
			}
			courses.add(title);
			
			/**表格数据行**/
			for(int i=0;i<sections.size();i++){
				Vector<String> row = new Vector<String>();
				
				Coursesection section = sections.get(i);
				
				for(int j=0;j<=weekInfo.getCells().size();j++){
					if(j==0) {
						row.add(section.getName()); 
					}else  
					{
						StringBuilder sb = new StringBuilder();
						WeekCell cell = weekInfo.getCells().get(j-1);
						String key = String.format("%s-%s", section.getId(),DateUtils.formatDate(cell.getDate(),"yyyy-MM-dd"));
						List<Course> inner = courseMap.get(key);
						if(inner!=null && inner.size()>0){
							
							for(Course c : inner){
								sb.append("<div class=\"course selected\">" + 
		                    		"<a href=\""+servletContext.getContextPath()+Global.getAdminPath()+"/qd/course/form?mode=week&year="+year+"&week="+week+"&id="+c.getId()+"\" title=\"老师1："+c.getTeacher()+" | 老师2："+c.getTeacher2()+"\">" + 
			                    		"<span class=\"course-left\">" + 
			                    			"<strong>"+ c.getSerial() +"</strong>" + 
			                    			"<strong>"+ c.getClevel() +"</strong>" + 
			                    		"</span>" + 
			                    		"<span class=\"course-middle\">" + 
			                    			"<strong>"+ c.getTheme() +"</strong>" + 
			                    			"<strong>"+ c.getSigins() +"/"+ c.getCapacity() +"</strong>" + 
			                    		"</span>" + 
			                    		"<span class=\"course-right\">" + 
			                    			//"<strong>"+ c.getSigins() +"/"+ c.getCapacity() +"</strong>" + 
			                    		"</span>" + 
		                    		"</a>" + 
		                    	"</div>");
								//sb.append("<a href=\""+servletContext.getContextPath()+Global.getAdminPath()+"/qd/course/form?id="+c.getId()+"\" style=\" color:#ff0000;\" title=\"主讲："+c.getTeacher()+" | 助教："+c.getTeacher2()+"\">"+c.getClevel() +"&nbsp"+c.getSerial()+"&nbsp"+c.getTheme()+"&nbsp;["+c.getClassroom()+"]</a>&nbsp;&nbsp;<span></span><br>");
							}
						}
						 
						sb.append("<div class=\"course selected plus\"><a href=\""+servletContext.getContextPath()+Global.getAdminPath()+"/qd/course/form?mode=week&year="+year+"&week="+week+"&sectionId="+section.getId()+"&date="+DateUtils.formatDate(cell.getDate(), "yyyy-MM-dd")+"\"><img style=\" border:none\" src=\""+servletContext.getContextPath()+"/assets/images/add.png\" title=\"点击排课\"></a></div>");
						row.add(sb.toString());
					}
				}
				courses.add(row);
			}
			
			//取L1，L2-L6所有主题
			List<String> themesOfL1 =  coursethemeService.getThemeNames("L1", UserUtils.getCenter().getId());
			List<String> themesOfLx = coursethemeService.getThemeNames(null, UserUtils.getCenter().getId());
			
			model.addAttribute("l1", themesOfL1);
			model.addAttribute("lx", themesOfLx);
			
			model.addAttribute("yearPre", yearPre);
			model.addAttribute("yearNow", yearNow);
			model.addAttribute("yearNext", yearNext);
			model.addAttribute("year", year);
			//model.addAttribute("yearList",yearList);
			
			model.addAttribute("weekPre", weekPre);
			model.addAttribute("weekNow", weekNow);
			model.addAttribute("weekNext", weekNext);
			model.addAttribute("week", week);
			model.addAttribute("weekList",weekList);
			
			model.addAttribute("weekInfo", weekInfo);
			model.addAttribute("sections", sections);
			
			model.addAttribute("courses",courses);
		}else if(mode.equals("month")){
			//月日历
			viewName = "modules/qd/courseListMonth";
			
			
		}else if(mode.equals("day")){
			//日日历
			viewName = "modules/qd/courseListDay";
			
		}
		
		return viewName;
	}
	
	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = "order")
	public String order(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		int courseId = StringUtils.toInteger(request.getParameter("courseId"));
		
		List<HashMap<String, Object>> infos = courseService.order(request);
		
		redirectAttributes.addAttribute("id", courseId);
		redirectAttributes.addFlashAttribute("infos", infos);
		
		String mode = request.getParameter("mode");
		if(mode.equals("week")){
			redirectAttributes.addAttribute("mode", mode);
			redirectAttributes.addAttribute("year", request.getParameter("p1"));
			redirectAttributes.addAttribute("week", request.getParameter("p2"));
		}
		
		return "redirect:"+Global.getAdminPath()+"/qd/course/form";
	}
	
	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = "cancel")
	public String cancel(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		int courseId = StringUtils.toInteger(request.getParameter("courseId"));
		
		String message = "";
		HashMap<String,Object> map = courseService.cancelOrder(request);	
		if(map != null){
			message = (String) map.get("errMessage");
		}

		redirectAttributes.addAttribute("id", courseId);
		redirectAttributes.addFlashAttribute("message", message);
		
		String mode = request.getParameter("mode");
		if(mode.equals("week")){
			redirectAttributes.addAttribute("mode", mode);
			redirectAttributes.addAttribute("year", request.getParameter("p1"));
			redirectAttributes.addAttribute("week", request.getParameter("p2"));
		}
		
		return "redirect:"+Global.getAdminPath()+"/qd/course/form";
	}
	
	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = "leave")
	public String leave(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		int courseId = StringUtils.toInteger(request.getParameter("courseId"));
		
		String message = "请假失败";
		HashMap<String,Object> map = courseService.leaveCourse(request);
		if(map != null){
			message = (String) map.get("message");
		}
 
		redirectAttributes.addAttribute("id", courseId);
		redirectAttributes.addFlashAttribute("message", message);
		
		String mode = request.getParameter("mode");
		if(mode.equals("week")){
			redirectAttributes.addAttribute("mode", mode);
			redirectAttributes.addAttribute("year", request.getParameter("p1"));
			redirectAttributes.addAttribute("week", request.getParameter("p2"));
		}
		
		return "redirect:"+Global.getAdminPath()+"/qd/course/form";
	}
	
	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = "abort")
	public String abort(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		String message = "";
		
		Course course = courseService.get(request.getParameter("courseId"));
		/**第一步：没有过上课时间，不允许进行中止操作**/
		String onDate = DateUtils.formatDate(course.getOndate(),"yyyy-MM-dd");
		String section = course.getSection();
		
		Date start = null,end = null; 
		try{
			if(!StringUtils.isEmpty(section)){
				String[] sections = section.split("-");
				if(sections!=null && sections.length==2){
					start = DateUtils.parseDate(onDate+" "+sections[0],"yyyy-MM-dd hh:mm");
					end = DateUtils.parseDate(onDate+" "+sections[1],"yyyy-MM-dd hh:mm");
				}else{
					start = DateUtils.parseDate(onDate+" 00:00","yyyy-MM-dd hh:mm");
					end = DateUtils.parseDate(onDate+" 00:00","yyyy-MM-dd hh:mm");
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		if(start!=null && end !=null){
			Date now = new Date();
			if(now.compareTo(end)<=0 && now.compareTo(start)>=0){
				message = courseService.abortOrder(request);
			}else{
				message = "未到上课时间，不允许中止";
			}
		}

		redirectAttributes.addAttribute("id", course.getId());
		redirectAttributes.addFlashAttribute("message", message);
		
		String mode = request.getParameter("mode");
		if(mode.equals("week")){
			redirectAttributes.addAttribute("mode", mode);
			redirectAttributes.addAttribute("year", request.getParameter("p1"));
			redirectAttributes.addAttribute("week", request.getParameter("p2"));
		}
		
		return "redirect:"+Global.getAdminPath()+"/qd/course/form";
	}
	
	@RequiresPermissions("qd:course:edit")
	@RequestMapping(value = "time")
	public String time(Course course,HttpServletRequest request, Model model) {
		//获取所有时段
		List<Coursesection> coursesectionList = coursesectionService.findList(new Coursesection());
		model.addAttribute("sectionList",coursesectionList);
		model.addAttribute("course", course);
		
		return "modules/qd/courseTime";
	}
	
	@RequiresPermissions("qd:course:edit")
	@RequestMapping(value = "stop")
	public String stop(Course course,HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		courseService.stopCourse(course);
		
		String mode = request.getParameter("mode");
		if(mode.equals("week")){
			redirectAttributes.addAttribute("mode", mode);
			redirectAttributes.addAttribute("year", request.getParameter("p1"));
			redirectAttributes.addAttribute("week", request.getParameter("p2"));
		}
		
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/qd/course/?repage";
	}

	
	@RequiresPermissions("qd:course:edit")
	@RequestMapping(value = "timesave")
	public String timeSave(Course course,HttpServletRequest request, Model model) {
		if (!beanValidator(model, course)){
			return form(course, request, model);
		}
		
		String ondatePre = request.getParameter("ondatePre");
		String section = request.getParameter("sectionPre");
		
		Date datePre = null;
		try {
			datePre = DateUtils.parseDate(ondatePre, "yyyy-MM-dd");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		courseService.save(course);
		
		/**发送调整时间通知**/
		List<HashMap<String,Object>> orderedStudents = courseService.getCourseStudents(course.getType(),StringUtils.toInteger(course.getId()));
		for(HashMap<String,Object> orderedStudent : orderedStudents){
			int memberId = StringUtils.toInteger(orderedStudent.get("memberId"));//会员编号
			int studentId = StringUtils.toInteger(orderedStudent.get("studentId")); //学员编号
			
			SimpleDateFormat df = new SimpleDateFormat("MM月dd日");
			String message = CourseTimeChanged.content;
			message = message.replace(MsgTemplate.dateChanged, df.format(course.getOndate()));
			message = message.replace(MsgTemplate.sectionChanged, course.getSection());
			message = message.replace(MsgTemplate.date, df.format(datePre));
			message = message.replace(MsgTemplate.section, section);
			message = message.replace(MsgTemplate.level, course.getClevel());
			message = message.replace(MsgTemplate.serial, course.getSerial());
			message = message.replace(MsgTemplate.theme, course.getTheme());
			
			String pushMsg = CourseTimeChanged.push;
			pushMsg = pushMsg.replace(MsgTemplate.dateChanged, df.format(course.getOndate()));
			pushMsg = pushMsg.replace(MsgTemplate.sectionChanged, course.getSection());
			pushMsg = pushMsg.replace(MsgTemplate.date, df.format(datePre));
			pushMsg = pushMsg.replace(MsgTemplate.section, section);
			pushMsg = pushMsg.replace(MsgTemplate.level, course.getClevel());
			pushMsg = pushMsg.replace(MsgTemplate.serial, course.getSerial());
			pushMsg = pushMsg.replace(MsgTemplate.theme, course.getTheme());
			
			messageService.sendAndPush(CourseTimeChanged.category, String.valueOf(studentId), CourseTimeChanged.title, message, String.valueOf(memberId), pushMsg);
		}
		
		model.addAttribute("script","<script type=\"text/javascript\">window.onload=function(){save();}</script>");
		
		return time(course,request,model);
	}
	
	@RequiresPermissions("qd:course:view")
	@RequestMapping(value = "form")
	public String form(Course course,HttpServletRequest request, Model model) {
		
		Map<String, ?> maps = RequestContextUtils.getInputFlashMap(request); 
		
		if(maps!=null){
			/**约课提示信息**/
			@SuppressWarnings("unchecked")
			List<HashMap<String, Object>> infos = (List<HashMap<String, Object>>) maps.get("infos");
			
			StringBuilder sb = new StringBuilder();
			
			if(infos!=null){
				for(HashMap<String, Object> map : infos){
					boolean state = Boolean.parseBoolean(map.get("state").toString());
					
					sb.append(String.format("学员[%s]预约%s %s<br/>", map.get("studentName"),(state ? "成功":"失败"),map.get("message")));
				}
				model.addAttribute("infos", "<script type=\"text/javascript\">showModal('预约结果通知','"+sb.toString()+"');</script>");
			}
			/**取消约课提示信息**/
			String message = (String) maps.get("message");
			if(!StringUtils.isEmpty(message)){
				if(StringUtils.isEmpty(message)){
					model.addAttribute("infos", "<script type=\"text/javascript\">showModal('取消结果通知','"+message+"');</script>");
				}
			}
		}
		
		//请求排课时间
		String date = request.getParameter("date");
		if(!StringUtils.isEmpty(date)){
			course.setOndate(DateUtils.parseDate(date));
		}
		
		//请求排课时间段
		String sectionId = request.getParameter("sectionId");
		if(!StringUtils.isEmpty(sectionId)){
			course.setSectionId(StringUtils.toInteger(sectionId));
		}
		
		List<Coursesection> sectionList = coursesectionService.findList(new Coursesection());
		model.addAttribute("sectionList",sectionList);
		
		//获取所有的课程阶段
		List<Courselevel> levelList = courselevelService.findList(new Courselevel());
		model.addAttribute("levelList",levelList);
		
		//获取所有教室
		List<Classroom> classroomList = classroomService.findList(new Classroom());
		model.addAttribute("classroomList",classroomList);
		
		//获取所有时段
		List<Coursesection> coursesectionList = coursesectionService.findList(new Coursesection());
		model.addAttribute("coursesectionList",coursesectionList);
		for(Coursesection s : coursesectionList){
			if(s.getId().equals(sectionId)){
				course.setSection(s.getName());
			}
		}
		
		//所有课程教师
		List<Teacher> teacherList = teacherService.findList(new Teacher());
		model.addAttribute("teacherList",teacherList);
		
		if(!StringUtils.isEmpty(course.getId())){
			/**如果是编辑**/
			
			//所有课程系列
			List<Courseserial> serialList = courseserialService.findListByLevel(course.getLevelId().toString());
			model.addAttribute("serialList",serialList);
			
			//标签数组
			String label = course.getLabel();
			List<String> labelList = new ArrayList<String>();
			if(label != null){
				String[] labels = label.split("\\|");
				for(String tempStr : labels){
					if(!StringUtils.isEmpty(tempStr)){
						labelList.add(tempStr);
					}
				}
				model.addAttribute("labelList", labelList);
			}
			
			//所有课程主题
			Coursetheme ext = new Coursetheme();
			ext.setLevel(new Courselevel(course.getLevelId().toString()));
			ext.setSerial(new Courseserial(course.getSerialId().toString()));
			List<Coursetheme> themeList = coursethemeService.findList(ext);
			model.addAttribute("themeList",themeList);
			
		}else{
			/**如果是新增**/
			//设置中心
			User user = UserUtils.getUser();
			course.setCenterId(StringUtils.toInteger(user.getCenter().getId()));
		}
		
		//约课学员
		if(course.getId() != null && !course.getId().equals("")){
			CourseOrder courseOrder = new CourseOrder();
			courseOrder.setCourseId(Integer.valueOf(course.getId()));
			List<CourseOrder> studentList = courseOrderService.findOrderStudents(courseOrder);
			model.addAttribute("studentList", studentList);
		}
		
		//免费试听
		if(course.getId() != null && !course.getId().equals("")){
			Coursefree coursefree = new Coursefree();
			coursefree.setCourseId(Integer.valueOf(course.getId()));
			List<Coursefree> freeList = coursefreeService.findList(coursefree);
			model.addAttribute("freeList", freeList);
		}
		
		//课程 
		model.addAttribute("course", course);
		
		//所有课程图片
		Album ca = new Album();
		ca.setCategory("course");
		ca.setObjectId(StringUtils.toInteger(course.getId()));
		List<Album> courseAlbum = albumService.findList(ca);
		model.addAttribute("courseAlbum", courseAlbum);
		
		//所有课堂图片
		Album cla = new Album();
		cla.setCategory("classroom");
		cla.setObjectId(StringUtils.toInteger(course.getId()));
		List<Album> classroomAlbum = albumService.findList(cla);
		model.addAttribute("classroomAlbum", classroomAlbum);
		
		String mode = request.getParameter("mode");
		if(mode.equals("week")){
			model.addAttribute("mode",request.getParameter("mode"));
			model.addAttribute("p1", request.getParameter("year"));
			model.addAttribute("p2", request.getParameter("week"));
		}
		
		//判断是否已经有人预约了，课程的信息不能修改，除了：教室、老师、主题介绍、课程图片
		boolean readonly = courseService.getCourseReadonly(course);
		model.addAttribute("readonly",readonly);
		
		return "modules/qd/courseForm";
	}

	@RequiresPermissions(value={"qd:course:edit","qd:course:add"}, logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Course course, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, course)){
			return form(course, request, model);
		}
		
		/**设置中心**/
		User user = UserUtils.getUser();
		course.setCenterId(StringUtils.toInteger(user.getCenter().getId()));
		
		/**保存标签**/
		String[] labels = request.getParameterValues("labels");
		if(labels != null){
			StringBuffer buffer = new StringBuffer("|");
			for(String tempStr : labels){
				buffer.append(tempStr+"|");
			}
			course.setLabel(buffer.toString());
		}
		courseService.save(course);
		
		/**设置相册**/
		Album ca = new Album();
		ca.setCategory("course");
		ca.setObjectId(StringUtils.toInteger(course.getId()));
		albumService.deleteAll(ca);
		
		Album cla = new Album();
		cla.setCategory("classroom");
		cla.setObjectId(StringUtils.toInteger(course.getId()));
		albumService.deleteAll(cla);
		 
		String[] photos = request.getParameterValues("hid_photo_name");
		String[] remarks = request.getParameterValues("hid_photo_remark");
		if(photos!=null){
			for(int i=0;i<photos.length;i++){
				String photo = photos[i];
				String remark = remarks[i];
				
				if(!StringUtils.isEmpty(photo)){
					String[] parts = photo.split("\\|");
					if(parts!=null && parts.length>=6){
						Album album = new Album();
						album.setObjectId(StringUtils.toInteger(course.getId()));
						album.setCategory(parts[0]);
						album.setFileName(parts[1]);
						album.setOrginPath(parts[2]);
						album.setThumbPath(parts[3]);
						album.setAlbumSize(StringUtils.toInteger(parts[4]));
						album.setRemarks(remark);
						
						albumService.save(album);
					}
				}
			}
		}
		
		String mode = request.getParameter("mode");
		if(mode.equals("week")){
			redirectAttributes.addAttribute("mode", mode);
			redirectAttributes.addAttribute("year", request.getParameter("p1"));
			redirectAttributes.addAttribute("week", request.getParameter("p2"));
		}
		
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/qd/course/?repage";
	}
	
	@RequiresPermissions("qd:course:edit")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Course course, RedirectAttributes redirectAttributes) {
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				courseService.delete(new Course(id));
			}
		}else{
			courseService.delete(course);
		}
		
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/qd/course/?repage";
	}
	
	@RequiresPermissions("qd:course:edit")
	@RequestMapping(value = "copy")
	public String copy(HttpServletRequest request, Model model) {
		
		String year = (String) request.getParameter("year");
		String fyear = (String) request.getParameter("fyear");
		String tyear = (String) request.getParameter("tyear");
		
		String nweek = (String) request.getParameter("nweek");
		String fweek = (String) request.getParameter("fweek");
		String tweek = (String) request.getParameter("tweek");
		
		String btnSearchSubmit = (String) request.getParameter("btnSearchSubmit");
		String btnCopySubmit = (String) request.getParameter("btnCopySubmit");
		
		Calendar now = Calendar.getInstance();
		if(StringUtils.isEmpty(year)){
			year = String.valueOf(now.get(Calendar.YEAR));
		}
		
		if(StringUtils.isEmpty(fyear)){
			fyear = String.valueOf(now.get(Calendar.YEAR));
		}
		
		if(StringUtils.isEmpty(tyear)){
			tyear = String.valueOf(now.get(Calendar.YEAR));
		}
		
		List<WeekInfo> weeks = CalendarUtils.getWeeksInYear(StringUtils.toInteger(year));
		List<WeekInfo> fweeks = CalendarUtils.getWeeksInYear(StringUtils.toInteger(fyear));
		List<WeekInfo> tweeks = CalendarUtils.getWeeksInYear(StringUtils.toInteger(tyear));
		
		String js = "";
		
		List<Course> courseList = null;
		
		//搜索按钮点击
		if(!StringUtils.isEmpty(btnSearchSubmit)){
			if(StringUtils.isEmpty(nweek)){
				js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"请选择复制从星期\");</script>";
			}else{
				try{
					String[] weektime = nweek.split("~");
					
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					
					Date start = sdf.parse(String.format("%s 00:00:00", weektime[0]));
					Date end = sdf.parse(String.format("%s 23:59:59", weektime[1]));
					
					courseList = courseService.findListByWeek(new Course(), start, end);
				}catch(Exception ex){
					js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"选择复制从星期格式异常\");</script>";
				}
			}
		}
		
		//开始复制按钮
		if(!StringUtils.isEmpty(btnCopySubmit)){
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			
			if(StringUtils.isEmpty(fweek) || StringUtils.isEmpty(tweek)){
				js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"请选择复制到星期\");</script>";
			}else{
				try{
					
					String[] fweektime = fweek.split("~");
					
					Date fstart = sdf.parse(String.format("%s 00:00:00", fweektime[0]));
					//Date fend = sdf.parse(String.format("%s 23:59:59", fweektime[1]));
					
					String[] tweektime = tweek.split("~");
					
					//Date tstart = sdf.parse(String.format("%s 00:00:00", tweektime[0]));
					Date tend = sdf.parse(String.format("%s 23:59:59", tweektime[1]));
					
					if(tend.before(fstart)){
						js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"请选择正确的复制到周的范围\");</script>";
					}else{
						int days = CalendarUtils.daysBetween(fstart, tend);
						
						if(days>0 && days<=30){
							/**开始复制课程-begin**/
							String[] ids = request.getParameterValues("checkall");
							
							if(ids!=null && ids.length>0){
								for(String courseId : ids){
									Course course = courseService.get(courseId);
									
									List<Date> ondates = CalendarUtils.calcOnDate(course.getOndate(),fstart,tend);
									
									if(course!=null && ondates!=null){
										for(Date ondate : ondates){
											course.setIsNewRecord(true);//设置为新纪录
											course.setOndate(ondate);
											
											courseService.save(course);
											
											/**设置相册**/
											Album ca = new Album();
											ca.setCategory("course");
											ca.setObjectId(StringUtils.toInteger(courseId));
											List<Album> cas = albumService.findList(ca);
											
											for(Album al : cas){
												al.setIsNewRecord(true);
												al.setObjectId(StringUtils.toInteger(course.getId()));
												albumService.save(al);
											}
											
											Album cla = new Album();
											cla.setCategory("classroom");
											cla.setObjectId(StringUtils.toInteger(courseId));
											List<Album> clas = albumService.findList(cla);
											
											for(Album al : clas){
												al.setIsNewRecord(true);
												al.setObjectId(StringUtils.toInteger(course.getId()));
												albumService.save(al);
											}
										}
									}
								}
								js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"课程复制完成\");</script>";
							}else{
								js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"请选择需要复制的课程\");</script>";
							}
							/**开始复制课程-end**/
						}else{
							js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"选择复制到周的范围超过30天\");</script>";
						}
					}
					
				}catch(Exception ex){
					logger.error("复制课程出现异常", ex);
					js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"复制课程出现异常\");</script>";
				}
			}
			
			if(!StringUtils.isEmpty(nweek)){
				try{
					String[] weektime = nweek.split("~");
					
					Date start = sdf.parse(String.format("%s 00:00:00", weektime[0]));
					Date end = sdf.parse(String.format("%s 23:59:59", weektime[1]));
					
					courseList = courseService.findListByWeek(new Course(), start, end);
				}catch(Exception ex){
					js = "<script type=\"text/javascript\">jsdialog(\"温馨提示\",\"选择复制从星期格式异常\");</script>";
				}
			}
		}
		
		model.addAttribute("year", year);
		model.addAttribute("fyear", fyear);
		model.addAttribute("tyear", tyear);
		
		model.addAttribute("weeks", weeks);
		model.addAttribute("fweeks", fweeks);
		model.addAttribute("tweeks", tweeks);
		
		model.addAttribute("nweek", nweek);
		model.addAttribute("fweek", fweek);
		model.addAttribute("tweek", tweek);
		
		model.addAttribute("js", js);
		
		model.addAttribute("courseList",courseList);
		
		return "modules/qd/courseCopy";
	}
}
